<?php
namespace app\common\service\impl;
use app\common\enums\ResultEnum;
use app\common\exception\ZeduException;
use app\common\model\LongRent;
use app\common\model\RentDetails;
use app\common\model\RentLog;
use app\common\service\CommonService;
use app\common\service\LongRentService;
use think\facade\Log;
class LongRentServiceImpl implements LongRentService
{
    protected $longRent;
    protected $rentDetails;
    protected $rentLog;
    protected $commonService;
    
    public function __construct(LongRent $longRent,RentDetails $rentDetails,RentLog $rentLog,CommonService $commonService)
    {
        $this->longRent = $longRent;
        $this->rentDetails = $rentDetails;
        $this->rentLog = $rentLog;
        $this->commonService = $commonService;
    }
    
   
    public function save(array $data)
    {

        $longRentData = [];
        $res = $this->longRent->where(['contract_number'=>$data['formValidate']['contract_number']])->find();
        if($res){
            throw new ZeduException(['code'=>ResultEnum::PARAM_ERROR['code'],'msg'=>'合同编号已存在']);
        }
        if(!empty($data['cars'])){
            foreach ($data['cars'] as $value){
                $value['user_id'] = $data['formValidate']['user_id'];
                $value['agency_id'] = $data['formValidate']['agency_id'];   
                $value['contract_number'] = $data['formValidate']['contract_number'];
                $value['rent_man'] = $data['formValidate']['rent_man'];
                $value['type'] = $data['formValidate']['type'];
                $value['contract_status'] = 1;
                $value['dispatch_status'] = 1;
                $value['status'] = 1;
                $value['expire_time'] = $data['formValidate']['expire_time'];
                $value['contract_time'] = $data['formValidate']['contract_time'];
               
                $longRentData[] = $value;
            }
            
           try {
               $this->longRent->allowField(true)->saveAll($longRentData);
              
            } catch (\Exception $e) {
               Log::record('[ 长租表插入数据 ]'.$e->getMessage(),'error');
               return false;
            }
            return true;   
        }
        
    }
    
    
    
    public function index(array $where, int $page, int $length)
    {
        try {
            $model = LongRent::with('agency,user,brand')->where($where)->order('id', 'desc')
            ->paginate($length,false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$page,
            ]);
            
        } catch (\Exception $e) {
            Log::record('[ 长租列表 ]:'.$e->getMessage(),'error');
            return false;
        }
        return $model;
    }
    public function dispatch(array $data)
    {
        $data['dispatch_status'] = 2;
        
        try {
            $this->longRent->allowField(true)->save($data,['id'=>$data['id']]);
        } catch (\Exception $e) {
            Log::record('[ 插入发车数据 ]:'.$e->getMessage(),'error');
            return false;
        }
        return true; 
    }
     
    
    public function account(array $data)
    {
        $longRent = $this->longRent->where(['id'=>$data['id']])->find();
        $rentDetails = $this->rentDetails->where(['status'=>1,'contract_number'=>$longRent['contract_number']])->find();
         $details = [];
         if($rentDetails){
            
             $details = [
                 'number'=>$rentDetails['number'] + 1,
                 'receive_money'=>$rentDetails['receive_money'] + $longRent['service_money'] +$longRent['rent_money'],
                 'rent_number'=>$rentDetails['rent_number'] + 1,
             ];    
             
             try {
                 $this->rentDetails->save($details,['id'=>$rentDetails['id']]);
                 return true;
             } catch (\Exception $e) {
                 Log::record('[ 长租明细列表写入数据 ]:'.$e->getMessage(),'error');
                 return false;
             }
             
         }else{
            
             $details = [
                 'agency_id'=>$longRent['agency_id'],
                 'user_id'=>$longRent['user_id'],
                 'brand_id'=>$longRent['brand_id'],
                 'contract_number'=>$longRent['contract_number'],
                 'type'=>$longRent['type'],
                 'rent_man'=>$longRent['rent_man'],
                 'contract_time'=>$longRent['contract_time'],
                 'expire_time'=>$longRent['expire_time'],
                 'rent_money'=>$longRent['rent_money'],
                 'service_money'=>$longRent['service_money'],
                 'rent_price'=>$longRent['rent_money'] + $longRent['service_money'],
                 'number'=>1,
                 'receive_money'=>$longRent['rent_money'] + $longRent['service_money'],
                 'rent_number'=>1,
                 'start_time'=>$longRent['dispatch_time'],
                 'end_time'=>mktime(0, 0, 0, date("m",strtotime($longRent['dispatch_time']))  , date("d",strtotime($longRent['dispatch_time']))+30, date("Y",strtotime($longRent['dispatch_time']))),
                 'belongs_month'=>date('Y-m',strtotime($longRent['dispatch_time'])),
                 'ought_time'=>$longRent['dispatch_time'],
                 'status'=>1,
             ];   
             
            try {
                 $this->rentDetails->create($details);
                 return true;
             } catch (\Exception $e) {
                 Log::record('[ 长租明细列表写入数据 ]:'.$e->getMessage(),'error');
                 return false;
             } 
             
         }
         
    }

    public function edit(array $data){
        $value = $this->longRent->where(['id'=>$data['id']])->value($data['key']);
        
        $dateArr = ['contract_time','expire_time','back_time','deposit_time'];
        if(in_array($data['key'],$dateArr)){
            $value = date('Y-m-d',$value);
        }
       
        $this->longRent->startTrans();
        try{
             
             $this->longRent->save([$data['key']=>$data['value']],['id'=>$data['id']]);
             
             if($this->longRent->update_time){
                 $model = $this->recordLog($data,$value,$this->longRent[$data['key']]);
                
                 if($model->id){
                     $this->longRent->commit();
                     return $this->longRent;
                 }else{
                     $this->longRent->rollback();
                     return false;
                 }
                 
             }else{
                 $this->longRent->rollback();
                 return false;
             }

        }catch(\Exception $e){
            $this->longRent->rollback();
            Log::record('[ 长租列表更新数据 ]:'.$e->getMessage(),'error');
            return false;
        }
        
    }


    public function uploadFile(array $data){

        $uploadData = [];
        $createData = [];
        $agency = [];
        $brand = [];
        $user = [];
        foreach ($data as $value) {
            
            $uploadData['car_sn'] = $value[0]??'';
            $agency['name'] = $value[1]??'';
            $uploadData['agency_id'] = $this->commonService->findAgency($agency);
            $brand['name'] = $value[2]??'';
            $uploadData['brand_id'] = $this->commonService->findBrand($brand);
            $type = $value[3]??'';
            switch ($type) {
                case '长租':
                    
                    $uploadData['type'] = 1;
                    break;
                case '以租代购':
                    
                    $uploadData['type'] = 2;
                    break;
                case '共享车主':
                    
                    $uploadData['type'] = 3;
                    break;
                case '短租':
                    
                    $uploadData['type'] = 4;
                    break;
                default:
                    $uploadData['type'] = null;
                    break;
            }
            $user['name'] = $value[4]??'';
            $uploadData['user_id'] = $this->commonService->findUser($user);
            $contractNumber = $value[5];
            $uploadData['contract_number'] = $this->findContractNo($contractNumber);
            $uploadData['contract_status'] = 1;
            $uploadData['rent_man'] = $value[7]??'';
            $uploadData['contract_time'] = $value[8]??'';
            $uploadData['expire_time'] = $value[9]??'';
            $uploadData['dispatch_man'] = $value[10]??'';
            $uploadData['dispatch_time'] = $value[11]??'';
            $uploadData['back_time'] = $value[12]??'';
            $uploadData['period'] = $value[13]??'';
            $uploadData['deposit'] = $value[14]??'';
            $uploadData['rent_money'] = $value[15]??'';
            $uploadData['service_money'] = $value[16]??'';
            $uploadData['deposit_time'] = $value[18]??'';
            $uploadData['offsets_deposit'] = $value[20]??'';
            $uploadData['actual_money'] = $value[22]??'';
            $uploadData['notes'] = $value[24]??'';
            $uploadData['dispatch_status'] = 1;

            $createData[] = $uploadData;

        }

       
        try{

            $model = $this->longRent->saveAll($createData);

        }catch(\Exception $e){
            Log::record('[ 导入数据 ]:'.$e->getMessage(),'error');
            return false;
        }

        return $model;
        
    }

    public function findContractNo($param){
        if($param){
            return $param;
        }else{
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>'合同编号不能为空']);
        }
    }
    
    public function delete(int $id)
    {
        try {
            $this->longRent->destroy($id);
        } catch (\Exception $e) {
            Log::record('[ 删除数据 ]:'.$e->getMessage(),'error');
            return false;
        }
        return true;
    }

    public function recordLog($data,$oldValue,$value){
        $type = [
            'car_sn'=>1,
            'contract_number'=>2,
            'rent_man'=>3,
            'contract_time'=>4,
            'expire_time'=>5,
            'back_time'=>6,
            'period'=>7,
            'deposit'=>8,
            'rent_money'=>9,
            'service_money'=>10,
            'deposit_time'=>11,
            'offsets_deposit'=>12,
            'actual_money'=>13,
            'notes'=>14
        ];
        
        $log = [];
        $log = ['rent_id'=>$data['id'],'admin_id'=>session('admin.id'),'type'=>$type[$data['key']],'old_value'=>$oldValue,'value'=>$value];
       
       try {
           
           $model = $this->rentLog->create($log);
           
       } catch (\Exception $e) {
           Log::record('[ 记录日志 ]'.$e->getMessage(),'error');
           return false;
       }
       
       return $model; 
        
    }
    
    
    public function rentLog(array $data)
    {
        try {
            $model = $this->rentLog::with('admin')->where(['rent_id'=>$data['id']])->order('id', 'desc')
            ->paginate($data['length'],false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$data['page'],
            ]);
        } catch (\Exception $e) {
            Log::record('[ 查询日志 ]'.$e->getMessage(),'error');
            return false;
        }
        
        return $model;
    }
    public function changeStatus(array $data)
    {
        try {
            $this->longRent->save(['contract_status'=>$data['status']],['id'=>$data['id']]);
        } catch (\Exception $e) {
            Log::record('[ 更改状态]'.$e->getMessage(),'error');
            return false;
        }
        
        return true;
        
    }
    
    public function renew(array $data)
    {
        $longData = $this->longRent->where(['contract_number'=>$data['contract_number'],'user_id'=>$data['user_id']])->field('expire_time,id')->select();
       
        $longRent = json_decode($longData,true);
       
        if(empty($longRent)){
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>'合同编号不存在']);
        }
       $createData = [];
        $saveData = [];
        $this->longRent->startTrans();
        try {
            $this->longRent->save(['expire_time'=>$data['expire_time']],['contract_number'=>$data['contract_number'],'user_id'=>$data['user_id']]);
            if($this->longRent->update_time){
                $this->rentDetails->save(['expire_time'=>$data['expire_time']],['contract_number'=>$data['contract_number'],'user_id'=>$data['user_id']]);
                if($this->rentDetails->update_time){
                    foreach ($longRent as $value){
                        $createData['rent_id'] = $value['id'];
                        $createData['admin_id'] = session('admin.id');
                        $createData['type'] = 5;
                        $createData['old_value'] = $value['expire_time'];
                        $createData['value'] = $data['expire_time'];
                        $saveData[] = $createData;
                    }
                    
                    try {
                        $this->rentLog->saveAll($saveData);
                        $this->longRent->commit();
                        return true;
                    } catch (\Exception $e) {
                        Log::record('[ 日志添加数据 ]:'.$e->getMessage(),'error');
                        $this->longRent->rollback();
                        return false;
                    }
                    
                }else{
                    $this->longRent->rollback();
                    return false;
                }
                
            }else{
                $this->longRent->rollback();
                return false;
            }
            
        } catch (\Exception $e) {
            $this->longRent->rollback();
            Log::record('[ 更新到期日 ]'.$e->getMessage(),'error');
            return false;
        }
    }


}

